import { ITodoData } from "./js/typings";
import TodoEvent from "./js/TodoEvent";
;((doc) => {
  const oInput: HTMLInputElement = doc.querySelector("input");
  const oAddBtn: HTMLButtonElement = doc.querySelector("button");
  const OTodoList: HTMLElement = doc.querySelector(".todo-list");

  const todoData: ITodoData[] = [];
  const todoEvent: TodoEvent = new TodoEvent(todoData, OTodoList);

  const init = (): void => {
    bindEvent();
  };
  
  function bindEvent(): void {
    oAddBtn.addEventListener("click", handlerAddBtnAndEnter, false);
    oInput.addEventListener('keydown', handlerAddBtnAndEnter, false)
    OTodoList.addEventListener("click", handlerListClick, false);
  }
  function handlerAddBtnAndEnter(e: KeyboardEvent | MouseEvent) {
    if (e.type === "keydown") {
      e = e as KeyboardEvent
      let keycode = e.code
      if ( keycode === 'Enter') {
        actuatorEventCallback();
      }
    } else {
      actuatorEventCallback();
    };

  };
  function handlerListClick(e: MouseEvent): void {
    const tar = e.target as HTMLElement;
    const tagName = tar.tagName.toLowerCase();
    if (tagName === "input" || tagName === "button") {
      const id = parseInt(tar.dataset.id);
      switch (tagName) {
        case "input":
          todoEvent.toggleComlete(tar, id);
          break;
        case "button":
          todoEvent.removeTodo(tar, id);
          break;

        default:
          break;
      }
    }
  }

  function actuatorEventCallback() {
    const val: string = oInput.value.trim();
    if (val.length) {
      const result = todoEvent.addTodo(<ITodoData>{
        id: new Date().valueOf(),
        content: val,
        complete: false,
      });
      if (result && result === 1001) {
        alert("列表项已存在！");
        return;
      }
      oInput.value = "";
    }
  };
  init();
})(document);
